import { isObject } from "@utils";

/**
 * @description: 请求瓦片 Blob 数据
 * @private
 * @param {Object} options 配置项
 * @returns {Promise<Blob>}
 */
export const _fetchTileByBlob = (options: {
  url: string;
  method?:
    | "get"
    | "post"
    | "put"
    | "delete"
    | "GET"
    | "POST"
    | "PUT"
    | "DELETE";
  headers?: Record<string, string>;
}): Promise<Blob> =>
  new Promise<Blob>((resolve, reject) => {
    const { method = "get", url, headers = {} } = options;
    const xhr = new XMLHttpRequest();

    xhr.addEventListener("loadend", ({ target }) => {
      if (target instanceof XMLHttpRequest) {
        if (
          target.response instanceof Blob &&
          target.response.type.startsWith("image/")
        ) {
          resolve(target.response);
        } else {
          reject(new Error("瓦片内容无法解析"));
        }
      } else {
        reject(new Error("氢气失败"));
      }
    });
    xhr.addEventListener("error", (e) => {
      reject(e);
    });

    xhr.responseType = "blob";
    xhr.open(method.toLocaleUpperCase(), url);
    if (isObject(headers)) {
      Object.keys(headers).forEach((key) => {
        xhr.setRequestHeader(key, headers[key].toString());
      });
    }

    xhr.send();
  });
